package com.pactera.jep.service.sys.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.commons.StringUtils;
import com.pactera.jep.core.context.Context;
import com.pactera.jep.core.entity.Identity;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.service.sys.security.spring.bean.UserEntity;
import com.pactera.jep.service.sys.util.UserEntityUtil;
import com.pactera.jep.sys.code.NotifyConfigResult;
import com.pactera.jep.sys.model.NotifyConfig;
import com.pactera.jep.sys.model.Staff;
import com.pactera.jep.sys.service.NotifyConfigService;
import com.pactera.jep.sys.service.StaffService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.code.WebHeaderCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author Yangyao
 * @time 2018年06月26日 09:47
 * @company 文思海辉技术有限公司
 */
@Api(value = "系统公告配置")
@RestController
@RequestMapping("/notifyConfig")
public class NotifyConfigRestController extends BaseRestController<NotifyConfig> {
	Logger logger = LoggerFactory.getLogger(NotifyConfigRestController.class);

	@Autowired
	private NotifyConfigService notifyConfigService;

	@Autowired
	private StaffService StaffService;

	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(@ApiIgnore @RequestHeader(WebHeaderCode.X_USER_TOKEN) String token,
			Page<NotifyConfig> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {

		notifyConfigService.query(page, filters, orders);
	}

	/**
	 * 获取当前登录用户的通知配置
	 *
	 * @return
	 */
	@ApiOperation(value = "获取当前登录用户的通知配置")
	@GetMapping(value = "/getNotifyConfigId")
	public NotifyConfig getNotifyConfigId(String staffCode) {
		NotifyConfig tmp = new NotifyConfig();
		tmp.setStaffCode(staffCode);

		NotifyConfig config = notifyConfigService.get(tmp);
		if (config != null) {
			/* 只更新过黑名单，未配置通知。获取用户的黑名单配置 */
			if (config.getIsReceiveSms() == null && config.getBlacklist() != null) {
				NotifyConfig result = notifyConfigService.get(WebCode.NOTIFY_CONFIG_ID);
				result.setBlacklist(config.getBlacklist());
				result.setBlacklistText(config.getBlacklistText());
				return result;
			} else {
				return config;
			}
		}
		return notifyConfigService.get(WebCode.NOTIFY_CONFIG_ID);
	}

	/**
	 * 保存默认配置
	 *
	 * @param notifyConfig
	 * @return
	 */
	@ApiOperation(value = "保存一条数据")
	@PostMapping(value = "/save")
	public Map<String, Object> save(@RequestBody NotifyConfig notifyConfig) {

		Map<String, Object> tips = new HashMap<String, Object>();

		notifyConfig.setId(WebCode.NOTIFY_CONFIG_ID);

		Boolean isExist = notifyConfigService.exists(notifyConfig.getId());
		try {
			if (isExist) {
				notifyConfigService.updateSelective(notifyConfig);
			} else {
				notifyConfig.setIsReceiveEmail(NotifyConfigResult.REFUSE.getValue());
				notifyConfig.setIsReceiveSms(NotifyConfigResult.REFUSE.getValue());
				notifyConfig.setIsReceiveMsg(NotifyConfigResult.RECEIVE.getValue());
				notifyConfig.setIsReceiveRemind(NotifyConfigResult.RECEIVE.getValue());

				notifyConfigService.insert(notifyConfig);
			}

			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		} catch (ServiceException e) {
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}

	/**
	 * 保存自定义配置
	 *
	 * @param notifyConfig
	 * @return
	 */
	@ApiOperation(value = "保存一条数据")
	@PostMapping(value = "/saveConfig")
	public Map<String, Object> saveConfig(@RequestBody NotifyConfig notifyConfig) {

		Map<String, Object> tips = new HashMap<String, Object>();
		UserEntity userEntity = UserEntityUtil.getCurrentUser();
		Staff staff = StaffService.get(userEntity.getUserId());
		// UserProfile staff = UserProfileUtils.getUserProfile();
		notifyConfig.setStaffCode(staff.getStaffCode());
		notifyConfig.setStaffName(staff.getStaffName());

		if (WebCode.NOTIFY_CONFIG_ID.equals(notifyConfig.getId())) {
			notifyConfig.setId(null);
		}

		Boolean isExist = notifyConfigService.exists(notifyConfig.getId());
		try {
			if (isExist) {
				notifyConfigService.update(notifyConfig);
			} else {
				notifyConfigService.insert(notifyConfig);
			}

			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		} catch (ServiceException e) {
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}

	@ApiOperation(value = "通过员工code获取白名单")
	@GetMapping(value = "/getBlacklistByStaffCode/{blackList}")
	public Map<String, Object> getBlacklistByStaffCode(@PathVariable String blackList) {
		Map<String, Object> result = new HashMap<String, Object>();

		NotifyConfig notifyConfig = new NotifyConfig();
		Identity identity = Context.getIdentityContext().getIdentity();
		notifyConfig.setStaffCode(identity.getId());
		notifyConfig.setStaffName(identity.getName());

		NotifyConfig exist = notifyConfigService.get(notifyConfig);
		if (exist != null) {
			String blacklistOld = exist.getBlacklist();
			if (StringUtils.isNotEmpty(blacklistOld) && blacklistOld.indexOf(blackList) != -1) {
				result.put("isExist", true);
			} else {
				result.put("isExist", false);
			}
		}
		return result;
	}

	/**
	 * 加入黑名单
	 *
	 * @param
	 * @param
	 * @return
	 */
	@ApiOperation(value = "加入黑名单")
	@PutMapping(value = "/addBlacklist")
	public Map<String, Object> addBlacklist(@RequestBody JSONObject jsonObject) {

		Map<String, Object> tips = new HashMap<String, Object>();
		String blacklist = jsonObject.getString("blacklist");
		String blacklistName = jsonObject.getString("blacklistName");
		NotifyConfig notifyConfig = new NotifyConfig();
		Identity identity = Context.getIdentityContext().getIdentity();
		notifyConfig.setStaffCode(identity.getId());
		notifyConfig.setStaffName(identity.getName());

		NotifyConfig exist = notifyConfigService.get(notifyConfig);
		try {
			if (exist != null) {
				String blacklistOld = exist.getBlacklist();
				String blacklistNameOld = exist.getBlacklistText();
				exist.setBlacklist(blacklist + "," + blacklistOld);
				exist.setBlacklistText(blacklistName + "," + blacklistNameOld);
				notifyConfigService.update(exist);
			} else {
				Staff staff = new Staff();
				staff.setStaffCode(notifyConfig.getStaffCode());
				staff = StaffService.get(staff);
				notifyConfig.setBlacklist(blacklist);
				notifyConfig.setBlacklistText(blacklistName);
				notifyConfig.setStaffPhone(staff.getMobile());
				notifyConfig.setStaffEmail(staff.getEmail());
				notifyConfigService.insert(notifyConfig);
			}

			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_ADD_BLT);
		} catch (ServiceException e) {
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_ADD_BLT);
		}
		return tips;
	}
}
